package com.yiidata.example.hadoop.mr;

import com.alibaba.fastjson.JSONObject;
import com.yiidata.amc.common.utils.ClassInJar;
import com.yiidata.amc.job.AbstractMapReduceJob;
import com.yiidata.amc.job.config.ParameterConfig;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.util.Optional;


/**
 *
 * <pre>
 *
 * Created by IntelliJ IDEA.
 * User: zhenqin
 * Date: 12-9-10
 * Time: 下午9:06
 * To change this template use File | Settings | File Templates.
 *
 * </pre>
 *
 * @author ZhenQin
 *
 */
public class WordCount extends AbstractMapReduceJob {

    int exitCode = -1;

    @Override
    public void callbackConf(Configuration conf) {
        conf.addResource("mapred-site.xml");
        conf.addResource("yarn-site.xml");
        System.out.println(conf.get("mapreduce.framework.name"));
    }

    @Override
    public void run(ParameterConfig parameter) {
        Job job = job();
        job.setJobName(Optional.ofNullable(
                parameter.getParameter("__TASK_NAME"))
                .orElse(this.getClass().getSimpleName()));
        //job.setJarByClass(WordCount.class);
        job.setJar(new ClassInJar(WordCount.class).getClassInjar());

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        job.setMapperClass(WordCountMapper.class);
        //job.setCombinerClass(WordCountReduce.class);
        job.setReducerClass(WordCountReduce.class);

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        try {
            FileInputFormat.setInputPaths(job, new Path(parameter.getParameter("input")));
            FileOutputFormat.setOutputPath(job, new Path(parameter.getParameter("output")));
            boolean success = job.waitForCompletion(true);
            exitCode = (success ? 0 : 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public int run(String[] args) throws Exception {
        JSONObject ps = new JSONObject();
        ps.put("input", args[0]);
        ps.put("output", args[1]);

        ParameterConfig parameterConfig = ParameterConfig.string2ParameterConfig(ps.toJSONString());
        run(parameterConfig);
        return exitCode;
    }



    public static void main(String[] args) throws Exception {
        System.exit(new WordCount().run(args));
    }

}
